package spatialmarketplace.cem.action;

import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.util.Log;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.ValidationError;
import spatialmarketplace.cem.model.Resource;
import spatialmarketplace.cem.dao.implementation.ResourceDaoImpl;
import spatialmarketplace.cem.model.Group;

/**
 * 
 * Display all resource data and display it on web page
 * User can share this resource to other groups
 * @author Camila @Implementation by Hung
 */
public class ResourceDetailActionBean extends BaseActionBean {

    private static final Log logger = Log.getInstance(ResourceDetailActionBean.class);
    private static final String FORM = "/WEB-INF/jsp/resource_detail.jsp";
    /**
     * Store resource data
     */
    protected Resource resource;
    /**
     * Store User Id that currently log on
     */
    protected Integer userId;
    /**
     * Check: user like resource or not
     */
    protected Boolean isLiked;
    /**
     * Check: user has rated the resource or not
     */
    protected Boolean isRated;

    /**
     * Store rate number that is voted by user Rate number is between 1 and 5
     */
    protected Integer rating;

    /**
     * Check resource is rated by user or not
     * @return yes or no
     */
    public Boolean getIsRated() {
        
        Integer resourceId = getContext().getGroupOrResourceId();
        Integer userId = this.userId;
        this.isRated = ResourceDaoImpl.getInstance().getVoted(resourceId,userId);
        return isRated;
    }

    public void setIsRated(Boolean isRated) {
        this.isRated = isRated;
    }
    
    /**
     * Get user's voted number that is stored in database.
     *
     * @return voted value
     */
    public Integer getRating() {
        Integer resourceId = getContext().getGroupOrResourceId();
        Integer userId = this.userId;
        this.rating = ResourceDaoImpl.getInstance().getRatedUserResource(userId, resourceId);
        return rating;
    }
    List<Group> groupsSharing = new ArrayList<Group>();

    public List<Group> getGroupsSharing() {
        return groupsSharing;
    }

    public void setGroupsSharing(List<Group> groupsSharing) {
        this.groupsSharing = groupsSharing;
    }

    public void setIsLiked(Boolean isLiked) {
        this.isLiked = isLiked;
    }

    /**
     * Check user has already liked resource or not. This information is stored
     * in database
     *
     * @return like or have not liked yet
     */
    public Boolean getIsLiked() {

        Integer resourceId = getContext().getGroupOrResourceId();
        Integer userId = this.userId;

        this.isLiked = ResourceDaoImpl.getInstance().getLiked(resourceId, userId);
        return this.isLiked;
    }

    /**
     * Get User Id that has being logged on. User Id is stored in Session
     *
     * @return
     */
    public Integer getUserId() {
        return getContext().getUserId();
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    /**
     * Display all information for the first opening web page.
     *
     * @return none
     */
    @DefaultHandler
    public Resolution form() {
        try {
            //Check user id in session to verify if the resource has been liked by the user.

            String rid = getContext().getRequest().getParameter("resourceId");
            if ((rid == null) || (rid == "")) {
                rid = getContext().getGroupOrResourceId().toString();
                // get default Resource Id
                if ((rid == null) || (rid == "")) {
                    rid = ResourceDaoImpl.getInstance().getDefaultResource().toString();
                }
            }
            getContext().setGroupOrResourceId(Integer.valueOf(rid));

            getContext().setForumBelongsToGroup(false);

            loadResourceDetail(getContext().getGroupOrResourceId());
            setUserId(getContext().getUserId());

            groupsSharing = loadGroupsSharing();
        } catch (Exception e) {
        }
        return new ForwardResolution(FORM);
    }

    public Resource getResource() {
        return resource;
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    /**
     * Call this method to load the initial information of the resource to
     * display.
     *
     * @param resourceId
     */
    protected void loadResourceDetail(Integer resourceId) {
        // get resource from database
        try {
            resource = ResourceDaoImpl.getInstance().read_Resource(resourceId);
        } catch (Exception e) {
        }
    }

    /**
     * Count the number of liked people on the resource and store it to database
     *
     * @return none
     */
    public Resolution likeResource() {
        //1. Increase like count of resource
        //2. Save a record into the table CEM_Resource_User with likedResource = true.
        Integer likeResource = Integer.valueOf(getContext().getRequest().getParameter("likesCounter"));
        Integer resourceId = Integer.valueOf(getContext().getRequest().getParameter("resourceId"));
        Integer userId = Integer.valueOf(getContext().getRequest().getParameter("userId"));
        ResourceDaoImpl.getInstance().setLikesCounter(resourceId, (likeResource + 1), userId);


        return new RedirectResolution(ResourceDetailActionBean.class);
    }

    public Resolution shareResourceOnFacebook() {
        //1. Share link in facebook.
        return new RedirectResolution(ResourceDetailActionBean.class);
    }

    public Resolution shareResourceOnTwitter() {
        //1. Share link in twitter.
        return new RedirectResolution(ResourceDetailActionBean.class);
    }

    public Resolution shareResourceOnGPlus() {
        //1. Share link in G+.
        return new RedirectResolution(ResourceDetailActionBean.class);
    }

    /**
     * Rate resource based on voting of many users. Update voted number to
     * resource that is voted by user Calculate voting rate and update it to
     * database
     *
     * @return
     */
    public Resolution rateResource() {
        //Save new Rate for resource.
        try {
            Float rating = Float.valueOf(getContext().getRequest().getParameter("star2"));
            Integer resourceId = Integer.valueOf(getContext().getRequest().getParameter("resourceId"));
            Integer userId = getContext().getUserId();

            ResourceDaoImpl.getInstance().setRating(resourceId, rating);
            ResourceDaoImpl.getInstance().setRateToUserResource(userId, resourceId, rating);
        } catch (Exception e) {
        }
        return new RedirectResolution(ResourceDetailActionBean.class);
    }

    /**
     * Load all groups that are shared the resource
     *
     * @return
     */
    public List<Group> loadGroupsSharing() {
        Integer resourceId = resource.getResourceId();

        try {
            groupsSharing = ResourceDaoImpl.getInstance().listGroupsSharing(resourceId);

        } catch (Exception e) {
        }
        return groupsSharing;
    }
}
